package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.UserLoginService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;

@Service
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {

        //1.校验参数
        if (StringUtils.isEmpty(dto.getName())  || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名和密码不能为空");
        }
        //2.数据库查询是否合法
        Wrapper wrapper = new QueryWrapper<>();
        ((QueryWrapper) wrapper).eq("name",dto.getName());

//        LambdaQueryWrapper wrapper1 = new LambdaQueryWrapper<>();
//        wrapper1.eq("name",dto.getName());
//
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.lambda().eq("name",dto.getName());
        List<AdUser> userList = this.list(wrapper); //查询用户信息
        if (userList!=null && userList.size()==1){
            AdUser adUser = userList.get(0);
            //根据查询的用户密码+库中的盐值 生成一个新的加密密码串,比较
            String salt = adUser.getSalt();
            String pwdsqlt = dto.getPassword()+salt;
            String newpwd = DigestUtils.md5DigestAsHex(pwdsqlt.getBytes());
            if (newpwd.equals(adUser.getPassword())){
                //用户输入的密码是对的  //3.生成token
                HashMap<Object, Object> hashMap = new HashMap<>();
                adUser.setPassword("");
                adUser.setSalt("");
                hashMap.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                hashMap.put("user",adUser);
                //4.把token,返回前端
                return ResponseResult.okResult(hashMap);
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
}
